<template>
    <div v-if="isAuth(['ROOT', 'WORKFLOW:APPROVAL', 'FILE:ARCHIVE'])">
        <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="searchHandle()">
            <el-form-item prop="creatorName">
                <el-input v-model="dataForm.creatorName" size="medium" placeholder="申请人" clearable="clearable"/>
            </el-form-item>
            <el-form-item prop="type">
                <el-select v-model="dataForm.type" placeholder="类别" size="medium" clearable="clearable">
                    <el-option label="会议申请" value="会议申请"></el-option>
                    <el-option label="员工请假" value="员工请假"></el-option>
                    <el-option label="报销申请" value="报销申请"></el-option>
                </el-select>
            </el-form-item>
            <!--   <el-form-item prop="instanceId">
                   <el-input v-model="dataForm.instanceId" size="medium" placeholder="实例编号" clearable="clearable"/>
               </el-form-item>-->
            <el-form-item>
                <el-button type="primary" size="medium" @click="searchHandle()">查询</el-button>
            </el-form-item>
            <el-form-item class="mold">
                <el-radio-group v-model="dataForm.status" size="medium" @change="searchHandle()">
                    <el-radio-button label="待审批"></el-radio-button>
                    <el-radio-button label="已审批"></el-radio-button>
                    <!--                    <el-radio-button label="已结束"></el-radio-button>-->
                </el-radio-group>
            </el-form-item>
        </el-form>
        <el-table
                ref="approvalTable"
                :data="dataList"
                border="border"
                v-loading="dataListLoading"
                cell-style="padding: 4px 0"
                size="medium"
                style="width: 100%;"
                @expand-change="expand"
                :row-key="getRowKeys"
                :expand-row-keys="expands"
        >
            <el-table-column prop="remark" header-align="center" align="center" type="expand">
                <template #default="scope">
                    <div class="content-container">
                        <table class="content-table">
                            <tbody v-if="scope.row.type == '会议申请'">
                            <tr>
                                <th><span>主题</span></th>
                                <td :title="scope.row.title">{{ scope.row.title }}</td>
                            </tr>
                            <tr>
                                <th><span>内容</span></th>
                                <td :title="content.desc">{{ content.desc }}</td>
                            </tr>
                            <tr>
                                <th><span>日期</span></th>
                                <td>{{ content.date }}&nbsp;&nbsp;&nbsp;{{ content.start }} ~ {{ content.end }}</td>
                            </tr>
                            <tr>
                                <th><span>地点</span></th>
                                <td>{{ content.place }}</td>
                            </tr>
                            <tr>
                                <th><span>申请人</span></th>
                                <td :title="content.name">{{ content.name }}</td>
                            </tr>
                            <tr>
                                <th><span>审批结果</span></th>
                                <td>
                                    <span v-if="scope.row.status != '审批通过'&& scope.row.status != '已同意'"
                                          style="color: orange;">审批中</span>
                                    <span v-if="scope.row.status == '审批通过' || scope.row.status == '已同意'"
                                          style="color: #17B3A3;">已同意</span>
                                </td>
                            </tr>
                            </tbody>
                            <tbody v-if="scope.row.type == '员工请假'">
                            <tr>
                                <th><span>请假原因</span></th>
                                <td :title="content.reason">{{ content.reason }}</td>
                            </tr>
                            <tr>
                                <th><span>请假类型</span></th>
                                <td>{{ content.type == 1 ? '病假' : '事假' }}</td>
                            </tr>
                            <tr>
                                <th><span>申请人</span></th>
                                <td>{{ content.name }}</td>
                            </tr>
                            <tr>
                                <th><span>起始时间</span></th>
                                <td>{{ content.start }}</td>
                            </tr>
                            <tr>
                                <th><span>截止时间</span></th>
                                <td>{{ content.end }}</td>
                            </tr>
                            <tr>
                                <!--状态：0：待提交，1请假中，2不同意，3已同意-->
                                <th><span>审批结果</span></th>
                                <td>
                                    <span v-if="scope.row.status != '审批通过'&& scope.row.status != '已同意'"
                                          style="color: orange;">审批中</span>
                                    <span v-if="scope.row.status == '审批通过' || scope.row.status == '已同意'"
                                          style="color: #17B3A3;">已同意</span>
                                </td>
                            </tr>
                            </tbody>
                            <tbody v-if="scope.row.type == '报销申请'">
                            <tr>
                                <th><span>申请人</span></th>
                                <td>{{ content.name }}</td>
                            </tr>
                            <tr>
                                <th><span>报销金额</span></th>
                                <td>{{ content.amount }}元</td>
                            </tr>
                            <tr>
                                <th><span>借款金额</span></th>
                                <td>{{ content.anleihen }}元</td>
                            </tr>
                            <tr>
                                <th><span>实际金额</span></th>
                                <td>{{ content.balance }}元</td>
                            </tr>
                            <tr>
                                <th><span>报销类型</span></th>
                                <td>{{ content.type }}</td>
                            </tr>
                            <tr>
                                <th><span>审批结果</span></th>
                                <td>
                                    <span v-if="scope.row.status != '审批通过'&& scope.row.status != '已同意'"
                                          style="color: orange;">审批中</span>
                                    <span v-if="scope.row.status == '审批通过' || scope.row.status == '已同意'"
                                          style="color: #17B3A3;">已同意</span>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <el-image
                                class="archive"
                                v-if="content.hasOwnProperty('files')"
                                :src="content.files[0].url"
                                :preview-src-list="archiveList"
                        ></el-image>
                        <el-image class="bpmn" :src="bpmnUrl" :preview-src-list="bpmnList"></el-image>
                    </div>
                </template>
            </el-table-column>
            <el-table-column type="index" header-align="center" align="center" label="序号" width="100"/>
            <el-table-column prop="title" header-align="center" align="center" v-if="dataForm.status=='待审批'"
                             label="审批事项" min-width="400"/>
            <el-table-column prop="taskName" header-align="center" align="center" v-if="dataForm.status=='已审批'"
                             label="任务名称" min-width="200"/>
            <el-table-column prop="type" header-align="center" align="center" label="类别" min-width="180"/>
            <el-table-column prop="creatorName" header-align="center" align="center" v-if="dataForm.status=='待审批'"
                             label="申请人" min-width="150"/>
            <el-table-column prop="taskAssignee" header-align="center" align="center" v-if="dataForm.status=='已审批'"
                             label="审批人" min-width="150"/>
            <el-table-column prop="createDate" header-align="center" v-if="dataForm.status=='待审批'" align="center"
                             label="发起日期" min-width="180"/>
            <el-table-column prop="createDate" v-if="dataForm.status=='已审批'" header-align="center" align="center"
                             label="审批日期" min-width="180"/>
            <el-table-column prop="status" header-align="center" align="center" label="状态" min-width="150">
                <!--            <el-table-column prop="status" v-if="dataForm.status=='已审批'" header-align="center" align="center" label="状态" min-width="150">-->
                <template #default="scope">
                    <span v-if="scope.row.status != '审批通过'&& scope.row.status != '已同意'"
                          style="color: orange;">审批中</span>
                    <span v-if="scope.row.status == '审批通过' || scope.row.status == '已同意'" style="color: #17B3A3;">
						已同意
					</span>
                    <!-- <span v-if="scope.row.status == '已结束' && scope.row.result == '不同意'" style="color: #f56c6c;">
                         已拒绝
                     </span>-->
                </template>
            </el-table-column>
            <el-table-column header-align="center" align="center" width="150" label="操作">
                <template #default="scope">
                    <el-button
                            type="text"
                            size="medium"
                            v-if="isAuth(['ROOT', 'WORKFLOW:APPROVAL']) && dataForm.status == '待审批' && !scope.row.filing "
                            @click="approveHandle(scope.row.taskId,scope.row.processName)"
                    >
                        审批
                    </el-button>
                    <el-button
                            type="text"
                            size="medium"
                            v-if="dataForm.status != '待审批'"
                            @click="viewHandle(scope.row)"
                    >
                        查看
                    </el-button>
                    <el-button
                            type="text"
                            size="medium"
                            v-if="isAuth(['ROOT', 'FILE:ARCHIVE'] ) && scope.row.filing"
                            @click="archive(scope.row.taskId,scope.row.businessKey,scope.row.processName)"
                    >
                        归档
                    </el-button>

                </template>
            </el-table-column>

        </el-table>
        <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="pageIndex"
                :page-sizes="[10, 20, 50]"
                :page-size="pageSize"
                :total="totalCount"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>

        <archive v-if="archiveVisible" ref="archive" @refreshDataList="loadDataList"></archive>

    </div>


</template>

<script>
    import Archive from './archive.vue';
    import Back from "./Back.vue";

    export default {
        components: {
            Archive,
            Back
        },
        data: function () {
            return {
                dialogVisible: false,
                pageIndex: 1,
                pageSize: 10,
                totalPage: 0,
                totalCount: 10,
                dataListLoading: false,
                dataListSelections: [],
                archiveVisible: false,
                backVisible: false,
                dataForm: {
                    creatorName: null,
                    type: null,
                    status: '待审批',
                    instanceId: null,
                    selectType: 0
                },
                dataList: [],
                content: {},
                bpmnUrl: null,
                bpmnList: [],
                archiveList: [],
                row: '',
                dataRule: {
                    creatorName: [{required: false, pattern: '^[\u4e00-\u9fa5]{2,20}$', message: '姓名格式错误'}],
                    instanceId: [
                        {
                            required: false,
                            pattern: '^[0-9A-Za-z\\-]{36}$',
                            message: '实例编号格式错误'
                        }
                    ],
                },
                rules: {
                    targetActivityId: [
                        {required: true, message: '请选择驳回目标', trigger: 'change'},
                    ]
                },
                formData: {
                    targetActivityId: null,
                },
                options: [], // 驳回目标选项
                expands: [],
                getRowKeys(row) {
                    return row.taskId;
                }
            };
        },
        /* watch: {
             async visible(newVal) {
                 if (newVal) {
                     this.options = []
                     // 查询可驳回节点
                     console.log("获取" + this.task)
                     /!*const {data} = await api.getBackNodes(this.task.taskId)
                     this.formData.targetActivityId = data[0].activityId
                     this.options = data*!/
                 }
             }
         },*/
        methods: {
            // 驳回提交表单数据
            submitForm(formName) {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        // 校验通过，提交表单数据
                        this.loading = true
                        try {
                            const params = {taskId: this.task.taskId, targetActivityId: this.formData.targetActivityId}
                            /* let response = await api.backTask(params)
                             if(response.code === 20000) {
                                 // 刷新数据
                                 this.$parent.fetchData()
                                 this.$message.success('提交成功')
                                 // 将表单清空
                                 this.$refs['formData'].resetFields()
                                 // 关闭窗口
                                 this.visible = false
                             }*/
                            this.loading = false
                        } catch (e) {
                            this.loading = false
                        }
                    }
                })
            },

            // 获取数据列表
            loadDataList: function () {
                let that = this;
                that.dataListLoading = true;
                let data = {
                    creatorName: that.dataForm.creatorName,
                    type: that.dataForm.type,
                    status: that.dataForm.status,
                    businessKey: that.dataForm.businessKey,
                    page: that.pageIndex,
                    length: that.pageSize
                };

                if (that.dataForm.status == '待审批') {
                    console.log("待审批" + data)
                    that.$http('approval/searchTaskByPage', 'POST', data, true, function (resp) {
                        console.log(resp.page)
                        let page = resp.page;
                        that.dataList = page.list;
                        that.totalCount = page.totalCount;
                        that.dataListLoading = false;
                    });
                } else if (that.dataForm.status == '已审批') {
                    console.log("已审批")
                    that.$http('approval/searchHistoryTaskByPage', 'POST', data, true, function (resp) {
                        console.log(resp.page)
                        let page = resp.page;
                        that.dataList = page.list;
                        that.totalCount = page.totalCount;
                        that.dataListLoading = false;
                    });
                    /*  that.$http('approval/searchTaskByPage', 'POST', data, true, function (resp) {
                          console.log(resp.page)
                          let page = resp.page;
                          that.dataList = page.list;
                          that.totalCount = page.totalCount;
                          that.dataListLoading = false;
                      });*/
                }
            },
            searchHandle: function () {
                console.log("已审批")
                this.$refs['dataForm'].validate(valid => {
                    if (valid) {
                        this.$refs['dataForm'].clearValidate();
                        if (this.dataForm.creatorName == '') {
                            this.dataForm.creatorName = null;
                        }
                        if (this.dataForm.instanceId == '') {
                            this.dataForm.instanceId = null;
                        }
                        if (this.pageIndex != 1) {
                            this.pageIndex = 1;
                        }
                        this.loadDataList();
                    } else {
                        return false;
                    }
                });
            },
            expand: function (row, expandedRows) {
                console.log(row + " " + expandedRows)
                let that = this;
                if (expandedRows.length > 0) {
                    that.expands = [];
                    console.log("状态" + row.type)
                    if (row) {
                        that.expands.push(row.taskId);
                        let data = {
                            businessKey: row.businessKey,
                            type: row.type,
                            // status: row.status
                        };

                        that.$http('approval/searchApprovalContent', 'POST', data, false, function (resp) {
                            let content = resp.content;
                            that.content = content;
                            console.log(content)
                            if (content.hasOwnProperty('files')) {
                                for (let one of content.files) {
                                    that.archiveList.push(one.url);
                                }
                            }

                            if (row.type == '报销申请') {
                                if (content.typeId == 1) {
                                    content.type = '普通报销';
                                } else if (content.typeId == 2) {
                                    content.type = '差旅报销';
                                }
                            }
                        });

                        that.bpmnUrl =
                            that.$baseUrl +
                            'approval/searchApprovalBpmn' +
                            '?instanceId=' +
                            row.processInstanceId +
                            '&time=' +
                            new Date().getTime();
                        that.bpmnList = [that.bpmnUrl];
                    }
                } else {
                    that.expands = [];
                }
            },

            approve: function (taskId, approval) {
                let that = this;
                that.dataListLoading = true;
                let data = {
                    taskId: taskId,
                    approval: approval
                };
                that.$http('approval/approvalTask', 'POST', data, true, function (resp) {
                    that.pageIndex = 1;
                    that.loadDataList();
                });
            },

            //否决
            disApprove: function (taskId, approval) {
                console.log(taskId + "" + approval)
                this.dialogVisible = true;
                console.log(this.dialogVisible)
                let that = this
                let data = {
                    taskId: taskId,
                    approval: approval,
                };
                that.$http('task/back', 'POST', data, true, function (resp) {
                    that.pageIndex = 1;
                    that.loadDataList();
                });
            },

            //同意或者否决
            approveHandle: function (taskId) {
                let that = this;
                that.$confirm('请选择对该条申请的处理意见', '提示', {
                    confirmButtonText: '同意',
                    cancelButtonText: '否决',
                    type: 'warning',
                    distinguishCancelAndClose: true,
                    callback: function (action) {
                        if (action == 'confirm') {
                            that.approve(taskId, '同意');
                        } else if (action == 'cancel') {
                            that.disApprove(taskId, "不同意");
                        }
                    }
                });
            },
            sizeChangeHandle(val) {
                this.pageSize = val;
                this.pageIndex = 1;
                this.loadDataList();
            },
            currentChangeHandle(val) {
                this.pageIndex = val;
                this.loadDataList();
            },
            viewHandle: function (row) {
                console.log(row)
                this.$refs.approvalTable.toggleRowExpansion(row, true);
            },

            archive: function (taskId, businessKey,processName) {
                console.log(taskId+"  "+businessKey+ ""+processName)
                this.archiveVisible = true;
                this.$nextTick(() => {
                    this.$refs.archive.init(taskId, businessKey,processName);
                });
            }
        },
        created: function () {
            this.loadDataList();
        },

    };
</script>

<style lang="less" scoped="scoped">
    @import url('approval.less');
</style>
